package cn.niit.smbms.interceptor;

import cn.niit.smbms.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 是否登录拦截器，主要拦截请求用户是否登录
 */

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor.preHandle..........");
        /**
         * 第一步：获取用户请求URL
         */
        String uri = request.getRequestURI();
        String url = request.getRequestURI().toString();
        log.info("uri: " + uri + " \t url:" + url);
        //删除这里的登录判断之后我们需要在白名单里面添加上我们的login页面，否则访问登录页面时会被拦截器拦截
        /*if(uri.equals("/login")){
            return true;
        }*/
        /**
         * 第二步：判断是否需要拦截
         */
        User user = (User) request.getSession().getAttribute("user");
        log.info("请求地址：{}, session 中的登录用户信息：{}", uri, user);
        if (null == user){
            System.out.println("拦截器 LoginInterceptor将执行preHandle将【" + uri + "】已拦截， 拦截原因：未登录！");
            //跳转至登录页面
//            request.getRequestDispatcher("/login").forward(request,response);
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor.postHandle..........");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor.afterCompletion..........");
    }
}
